import os

from utils.tools import read_excel
import re
import os
import pandas as pd


# 正则化匹配
def get_file_name(files_list, target_key):
    for file_name in files_list:
        if re.search(target_key, file_name):
            return file_name
    raise FileNotFoundError("未找到文件")


def statistical_analysis(df):
    """
    对给定的数据框执行统计分析
    """
    analysis_results = {}

    basic_stats = df.describe()
    return basic_stats


# 定义表格对应的数据
table_polution = {"XHK": "农田", "ZS": "市政污水", "DMH1": "湿地",
                  "DMH2": "湿地", "QSD": "酒厂废水", "NQ-上": "养殖场", "NQ-下": "养殖场"}

dir_path = r"D:\work\李俊杰2\ljj_repo\ljj_repo\water_tu\data\dianwei对应\2024-2"

files_list = os.listdir(dir_path)
sheet_name = "Result"
analysis = dict()
for target_key in table_polution.keys():
    try:
        print(target_key)
        files_name = get_file_name(files_list, target_key)
        path = os.path.abspath(os.path.join(dir_path, files_name))
        print(path)
        df = read_excel(path, sheet_name)
        basic_stats = statistical_analysis(df)
        analysis.update({target_key: basic_stats})
    except FileNotFoundError as e:
        print(f"文件未找到 {e}")

# 保存到一个 Excel 文件中
output_excel_file = "analysis_results_combined.xlsx"
with pd.ExcelWriter(output_excel_file) as writer:
    for target_key, basic_stats in analysis.items():
        basic_stats.to_excel(writer, sheet_name=table_polution[target_key])
